import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

const Login = () => import("@/views/Login.vue");
const Register = () => import("@/views/Register.vue");
const Layout = () => import("@/views/Layout.vue");
const Detail = () => import("@/views/Detail.vue");

const Like = () => import("@/views/Like.vue");
const Article = () => import("@/views/Article.vue");
const Collect = () => import("@/views/Collect.vue");
const User = () => import("@/views/User.vue");

import { getToken } from "@/utils/storage";
import { Toast } from "vant";

const routes = [
  {
    path: "/",
    redirect: "/article",
    component: Layout,
    children: [
      {
        path: "like",
        component: Like,
      },
      {
        path: "article",
        component: Article,
      },
      {
        path: "collect",
        component: Collect,
      },
      {
        path: "user",
        component: User,
      },
    ],
  },
  { path: "/login", component: Login },
  { path: "/register", component: Register },
  { path: "/detail/:id", component: Detail },
];

const router = new VueRouter({
  routes,
});

const whiteList = ["/login", "/register"];

router.beforeEach((to, from, next) => {
  const token = getToken();
  if (token) {
    next();
    return;
  }

  if (whiteList.includes(to.path)) {
    next();
    return;
  }

  Toast("您没有登录, 请登录");
  next("/login");
});

export default router;
